package org.ttitfly.ttcore.dao.account;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.QueryException;
import org.springframework.stereotype.Component;
import org.springside.modules.orm.hibernate.HibernateDao;
import org.ttitfly.ttcore.entity.account.Role;
import org.ttitfly.ttcore.entity.account.User;
import org.ttitfly.ttcore.so.account.RoleSO;
import org.ttitfly.ttcore.util.exception.DAOException;
import org.ttitfly.ttcore.util.query.ParameterResolver;
import org.ttitfly.ttcore.util.query.PropertyParameterResolver;
import org.ttitfly.ttcore.util.query.SQLBuilder;
import org.ttitfly.ttcore.util.query.SQueryBuilderByHibernate;

/**
 * 角色对象的泛型DAO.
 * 
 * @author calvin
 */
@Component
public class RoleDao extends HibernateDao<Role, Long> {

	private static final String QUERY_USER_BY_ROLEID = "select u from User u left join u.roleList r where r.id=?";

	/**
	 * 重载函数,因为Role中没有建立与User的关联,因此需要以较低效率的方式进行删除User与Role的多对多中间表.
	 */
	@SuppressWarnings("unchecked")
	@Override
	public void delete(Long id) {
		Role role = get(id);
		//查询出拥有该角色的用户,并删除该用户的角色.
		List<User> users = createQuery(QUERY_USER_BY_ROLEID, role.getId()).list();
		for (User u : users) {
			u.getRoles().remove(role);
		}
		super.delete(role);
	}
	
	public int getSORoleViewCount(RoleSO roleSO) {
		return Integer.parseInt(getRoles4List(roleSO, true).get(0).toString());

    }

    public List<Role> getSORoleView(RoleSO roleSO) {
    	return getRoles4List(roleSO,false);
    }
    
    @SuppressWarnings("unchecked")
    private <T> List<T> getRoles4List(RoleSO so, boolean isCount) {
        SQLBuilder pattern = new SQLBuilder("select distinct o ");

        pattern
                .append("FROM Role o  ");
        if (isCount) {
            pattern = new SQLBuilder("select count(distinct o) ");
            pattern.append("FROM Role o");
        }

        pattern.append("and upper(o.name) like :%name% ");
        
         if (!isCount) {
        	pattern.append("[alias=o] order by {o.id} desc");
        }

        ParameterResolver resolver = new PropertyParameterResolver(so);
        Query query = null;
        try {
            query = SQueryBuilderByHibernate.buildQuery(getSession(), pattern.toString(), resolver);
        } catch (QueryException e) {
            throw new DAOException(e.getMessage());
        }

        return query.list();
    }
    
    @SuppressWarnings("unchecked")
	public List<Role> getByIds(List<Long> ids) {
		Query query = getSession().createQuery("select o from Role o where o.id in (:ids) order by o.id");
		query.setParameterList("ids", ids);
		return ( List<Role> )query.list();
	}
}
